More results...

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
post
page
Python IDE Dashboard

Orbital Space Station – Emergency Exit Mission

Your Mission: Unlock the Emergency Exit Gate

You are aboard the Orbital Space Station K.101, orbiting the distant exoplanet K2-18b. After a catastrophic collision with space debris, the station is hurtling toward the planet’s atmosphere. You have minutes —maybe less— before the station overheats and disintegrates. Your only hope is to launch the emergency exit capsule, but the space station exit gate is sealed by 10 laser beams, each controlled by a unique logic gate circuit.

The control panel of these 10 laser beam is damaged, but the station’s technical documentation provides a truth table for each laser beam. Your task: Identify the correct logic gates circuits for each truth table to disable the lasers, one by one. Choose wisely—selecting the wrong gate will reset all 10 lasers, and time is running out!

Click on the following button to access this interactive challenge.
Orbital Space Station Emergency ExitOpen in New Window

Tagged with:

The Sieve of Eratosthenes

In this post we are going to investigate an ancient but highly effective algorithm known as the Sieve of Eratosthenes. This method, named after the Greek mathematician Eratosthenes (276 BC – 194B), is a simple and efficient way to find all prime numbers up to a specified integer. Let’s explore how it works!

What is the Sieve of Eratosthenes?

The Sieve of Eratosthenes is an algorithm that allows us to find all prime numbers up to any given limit. It does this by iteratively marking the multiples of each prime number starting from 2. The unmarked numbers that remain are prime numbers.

Step-by-Step Explanation

Let’s break down the process:

Step 1: Create a List of Numbers: Start by listing all the numbers from 2 to the desired upper limit. For example, if we want to find all prime numbers up to 100, we would list the numbers from 2 to 100. Imagine that all these numbers are in a large sieve. Progressively, the non primary numbers will be removed as they will “pass through” the sieve (see steps 2, 3 and 4)!

Step 2: Start with the First Number: The first number in the list is 2, which is a prime number. We will keep it (in our sieve) and eliminate all its multiples (i.e., 4, 6, 8, etc.) from the list because they are not prime.

Step 3: Move to the Next Unmarked Number: The next unmarked number is 3, which is also a prime number. We’ll keep it and eliminate all its multiples (i.e., 6, 9, 12, etc.) from the list.

Step 4: Repeat the Process: Continue this process with the next unmarked number, which is 5. Keep it and eliminate all its multiples. Repeat this process until you’ve gone through all the numbers in the list.

Step 5: Identify the Prime Numbers: The numbers that remain unmarked in the list are prime numbers.

Python Implementation

Here is a Python function that implements the Sieve of Eratosthenes algorithm:

Visual Representation

The following code uses Python Turtle to create a visual representation of the Sieve of Eratosthenes. The numbers in magenta are non primary numbers whereas the numbers in white are “left in the sieve” and are hence primary numbers:

Did you Know?

Eratosthenes was born in 276 BCE in Cyrene, a Greek city in modern-day Libya. He was a man of many talents and interests, which led him to study in various fields. He was a poet, an astronomer, a geographer, and a mathematician. He is especially known for his work on prime numbers (The Sieve of Eratosthenes) and for being the first person to accurately calculate the Earth’s circumference.

The Barnsley Fern Fractal

Nature has always been a source of inspiration for artists, mathematicians, and scientists alike. One of the most fascinating examples of this intersection is the Barnsley Fern, a mathematical construct that mimics the intricate patterns of a natural fern.

The Origins of the Barnsley Fern

The Barnsley Fern is named after mathematician Michael Barnsley, who introduced it in his book “Fractals Everywhere” published in 1988. Barnsley’s work on fractals and iterative function systems (IFS) revolutionised the way we understand complex natural patterns. The Barnsley Fern is a classic example of how simple mathematical rules can generate incredibly complex and beautiful structures.

The Mathematics Behind the Fern

The Barnsley Fern is created using a set of affine transformations, which include scaling, rotating, and translating points in a plane. These transformations are applied iteratively, starting from a single point. The process involves four specific transformations, each with its own probability:

  • Stem Transformation: Scales the fern vertically and places points along the stem.
  • Smaller Leaflets: Scales and rotates points to create the smaller leaflets.
  • Base Leaflets: Creates the larger leaflets at the base of the fern.

With each iteration, one of these transformations is applied based on its probability, gradually forming the shape of the fern.

Significance and Applications

The Barnsley Fern is significant in the field of fractal geometry, showing how simple mathematical rules can generate complex natural patterns. This has applications in computer graphics, where fractals are used to create realistic landscapes and vegetation. It also contributes to the study of chaos theory and dynamical systems.

Python Code

The following Python code demonstrates the iterative process. You can change within the code itself the number of dots to create different ferns.

Note that there is no Python challenge/task linked to this post. The aim of this post is just to investigate a beautiful example of the correlation between mathematics and nature. Whether you are a computer scientist, a mathematician, an artist, or simply someone who appreciates the beauty of nature, the Barnsley Fern is a fascinating subject that bridges the gap between abstract mathematics and the natural world.

Eratosthenes: The Ancient Scholar Who Measured the Earth

In the annals of scientific history, few names stand out as prominently as Eratosthenes. A polymath of the ancient world, Eratosthenes made significant contributions to various fields, including geography, mathematics, and astronomy. However, he is best known for his remarkable method to estimate the circumference of the Earth, a feat that has earned him the title of the “Father of Geography.”

Who Was Eratosthenes?

Eratosthenes was born in 276 BCE in Cyrene, a Greek city in modern-day Libya. He was a man of many talents and interests, which led him to study in various fields. He was a poet, an astronomer, a geographer, and a mathematician. His intellectual prowess caught the attention of the Ptolemaic rulers of Egypt, and he was invited to Alexandria to serve as the chief librarian of the Great Library of Alexandria, one of the most significant centres of learning in the ancient world.

Eratosthenes’ Method to Estimate the Earth’s Circumference

Eratosthenes’ most famous achievement is his calculation of the Earth’s circumference. His method was a brilliant combination of observation, geometry, and logical reasoning. Here’s a step-by-step breakdown of his approach:

Observation of the Sun’s Position: Eratosthenes noticed that on the summer solstice, the Sun was directly overhead in the city of Syene (modern-day Aswan, Egypt). This meant that the Sun’s rays were shining straight down a deep well, casting no shadow. However, at the same time in Alexandria, which is north of Syene, the Sun was not directly overhead. Instead, it cast a shadow, indicating that the Sun’s rays were coming in at an angle. (Note that the reason Eratosthenes chose Alexandria, is that he assumed Alexandria was located on the same meridian as Syene. This is a key criteria for this method to work. Though in reality this is not quite the case, which causes some slight inaccuracy in Eratosthenes estimate of the Earth circumference.)

Measurement of the Shadow’s Angle: In Alexandria, Eratosthenes measured the angle of the shadow cast by a vertical stick (a gnomon, the raised arm/stick of a sundial) at noon, on the summer solstice. He found that the angle was about 7.2 degrees, which is approximately 1/50th of a full circle (360 degrees).

Assumption of a Spherical Earth: Eratosthenes assumed that the Earth was a sphere, a concept that was widely accepted among educated Greeks at the time. He also assumed that the Sun’s rays were parallel, which is a reasonable approximation given the vast distance between the Earth and the Sun.

Calculation of the Earth’s Circumference: Using the information he had gathered, Eratosthenes reasoned that the distance between Alexandria and Syene was about 1/50th of the Earth’s circumference. He knew the distance between the two cities was approximately 5,000 stadia (a Greek unit of measurement: the exact length of a stadion is uncertain, but it is generally believed to be around 157.5 meters). So the distance between Syene and Alexandria is approximately 787.5km. By multiplying this distance by 50 to estimate the Earth’s circumference.

5,000 stadia * 50 = 250,000 stadia (or 787.5km * 50 = 39,375km)

This would make Eratosthenes’ estimate of the Earth’s circumference approximately 39,375 kilometres, which is remarkably close to the modern value of 40,075 kilometres.

Eratosthenes’ method to estimate the Earth’s circumference is a testament to the power of observation, reasoning, and mathematical prowess. His achievement is all the more remarkable considering the limited technology and resources available to him.

Python Challenge

Let’s write a small Python script to enable us to apply this method with different angle measurements made on different location on planet Earth, and let us see if we get a similar estimation of the Earth’s circumference.

Our Python program will need to:

    Take two inputs: the angle of the shadow and the distance in km from where the angle was measured and Syene’s well
    Use a mathematical formula based on Eratosthenes method:

    Output the estimated circumference of planet Earth in km, rounded to 3 decimal places
    Calculate the percentage of accuracy of this estimate, rounded to 2 decimal places, knowing that we now know that the circumference of planet Earth is 40,075km. The formula to claculate the percentage of accuracy is as follows:

    Python Code

    Type your code below:

    Testing

    To test your algorithm we have collected the approximate distances from Syene (Aswan, Egypt) of some different locations, all on the same meridian as Syene. For each location, we have recorded the angle of the shadow cast by the Sun at noon on the summer solstice (June 21st). Here is our test data:

    City Distance from Syene (km) Angle of the Shadow (degrees)
    Location 1: Alexandria, Egypt 800 7.2
    Location 2: 850 7.8
    Location 3: 2,000 18.2
    Location 4: 2,500 22.8
    Location 5: 2,800 25.6
    Location 6: 3,500 32.0
    Location 7: 4,000 36.6
    Location 8 9,000 82.2

    Can you check that your algorithm gives accurate estimate of the Earth circumference for each set of data provided in the table above.

    unlock-access

    Solution...

    The solution for this challenge is available to full members!
    Find out how to become a member:
    ➤ Members' Area

World Capital Cities – Python Quiz

Are you ready to test your knowledge of world capital cities? In this Python programming challenge, we’ll create an interactive quiz game. The game will display one capital city and four other non-capital cities in random order. Your task is to identify which city is a capital. If you guess correctly, you score a point and move on to the next question. The game ends when you guess incorrectly.

Using a List in Python

A list is a data structure used in python to store a collection of values. To complete this challenge we will use a list of cities which are not capital cities:

non_capital_cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix", 
   "Miami", "Toronto", "Vancouver", "Montreal", "Calgary",
   "Sydney", "Melbourne", "Brisbane", "Perth", "Adelaide",
   "Manchester", "Birmingham", "Liverpool", "Glasgow",
   "Marseille", "Lyon", "Toulouse", "Nice", "Nantes",
   "Hamburg", "Munich", "Cologne", "Frankfurt", "Stuttgart",
   "Milan", "Naples", "Turin", "Palermo", "Genoa",
   "Barcelona", "Valencia", "Seville", "Zaragoza", "Málaga",
   "Porto", "Funchal", "Braga", "Setúbal",
   "Thessaloniki", "Patras", "Larissa", "Heraklion", "Volos",
   "Yokohama", "Osaka", "Nagoya", "Sapporo", "Kobe",
   "Shanghai", "Guangzhou", "Shenzhen", "Chongqing", "Chengdu",
   "Mumbai", "Bangalore", "Hyderabad", "Ahmedabad", 
   "Rio de Janeiro", "São Paulo", "Salvador", "Fortaleza", "Belo Horizonte", 
   "Medellin", "Cali", "Barranquilla", "Cartagena",
   "Lima", "Arequipa", "Trujillo", "Chiclayo", "Iquitos",
   "Buenos Aires", "Córdoba", "Rosario", "Mendoza", "La Plata",
   "Auckland", "Christchurch", "Hamilton", "Tauranga",
   "Dubai", "Sharjah", "Al Ain", "Ajman", "Istanbul",
   "Izmir", "Bursa", "Antalya", "Jeddah", "Mecca", 
   "Medina", "Dammam", "Durban", "Johannesburg",
   "Mombasa", "Kisumu", "Nakuru", "Eldoret", "Lagos", 
   "Kano", "Ibadan", "Kaduna", "Port Harcourt", "Casablanca",
   "Fes", "Marrakech", "Tangier", "Accra", "Kumasi",
   "Tamale", "Sekondi-Takoradi", "Cape Coast", "Ho Chi Minh City", "Da Nang",
   "Hai Phong", "Can Tho", "Chiang Mai", "Pattaya", "Phuket",
   "Khon Kaen", "Penang", "Johor Bahru", "Ipoh", "Kuching",
    "Surabaya", "Bandung", "Medan", "Semarang"]

When using a list, we can access any value of the list using an index. The first value of the list, “New York” is at index 0.

print(non_capital_cities[0])  # New York
print(non_capital_cities[6])  # Toronto
print(non_capital_cities[18])  # Barcelona

The number of values stored in a list can be retrieved using the len() function:

number_of_cities = len(non_capital_cities)
print("There are " + str(number_of_cities) + " cities in this list.")

Using the random library in Python, we can randomly pick a value from the list. There are two ways this can be achieved:

import random

# Approach 1:
city = random.choice(non_capital_cities)
print(city)

# Approach 2:
index = random.randint(0,len(non_capital_cities)-1)
city = non_capital_cities[index]
print(city)

Using the random library you can also shuffle a list:

import random

cities = ["Paris", "Melbourne", "Istanbul", "Barcelona", "Kyoto"] 
random.shuffle(cities)
print(cities)

Finally, using a for loop you can access each value of a list one value at a time:

cities = ["Paris", "Melbourne", "Istanbul", "Barcelona", "Kyoto"] 

# Approach 1:
for city in cities:
   print(city)

# Approach 2:
for index in range(0, len(cities)):
   print(cities[index])

Using a Dictionary in Python

A dictionary also known as a hash table, is a data structure that stores a collection of key-value pairs. It is designed for efficient data retrieval, allowing values to be quickly accessed using their corresponding keys. Each key in a dictionary is unique and is associated with a specific value. To complete this quiz we will use a dictionary of capital cities where the keys will be the capital cities and the corresponding values will be the countries.

capital_cities = {
    "Paris": "France", "Berlin": "Germany", "Rome": "Italy",
    "Madrid": "Spain", "Lisbon": "Portugal", "Athens": "Greece",
    "Tokyo": "Japan",  "Beijing": "China", "New Delhi": "India",
    "Brasília": "Brazil", "Canberra": "Australia", "Ottawa": "Canada",
    "Washington, D.C.": "United States",  "Moscow": "Russia", "London": "United Kingdom",
    "Cairo": "Egypt", "Pretoria": "South Africa", "Nairobi": "Kenya",
    "Buenos Aires": "Argentina", "Lima": "Peru", "Oslo": "Norway",
    "Stockholm": "Sweden", "Helsinki": "Finland", "Copenhagen": "Denmark",
    "Wellington": "New Zealand", "Vienna": "Austria", "Brussels": "Belgium",
    "Amsterdam": "Netherlands", "Dublin": "Ireland", "Seoul": "South Korea",
    "Bangkok": "Thailand", "Kuala Lumpur": "Malaysia", "Jakarta": "Indonesia",
    "Singapore": "Singapore", "Ankara": "Turkey", "Riyadh": "Saudi Arabia",
    "Abu Dhabi": "United Arab Emirates", "Tehran": "Iran", "Baghdad": "Iraq",
    "Jerusalem": "Israel", "Mexico City": "Mexico", "Santiago": "Chile",
    "Bogotá": "Colombia", "Quito": "Ecuador", "Caracas": "Venezuela",
    "Sucre": "Bolivia", "Asunción": "Paraguay", "Montevideo": "Uruguay",
    "Georgetown": "Guyana", "Havana": "Cuba", "Santo Domingo": "Dominican Republic",
    "San Salvador": "El Salvador", "Guatemala City": "Guatemala", "Tegucigalpa": "Honduras",
    "Managua": "Nicaragua", "San José": "Costa Rica", "Panama City": "Panama",
    "Kingston": "Jamaica", "Nassau": "Bahamas", "Port-au-Prince": "Haiti",
    "Philipsburg": "Sint Maarten", "Reykjavik": "Iceland", "Warsaw": "Poland",
    "Budapest": "Hungary", "Bucharest": "Romania", "Sofia": "Bulgaria",
    "Zagreb": "Croatia", "Ljubljana": "Slovenia", "Bratislava": "Slovakia",
    "Prague": "Czech Republic", "Belgrade": "Serbia", "Sarajevo": "Bosnia and Herzegovina",
    "Podgorica": "Montenegro", "Pristina": "Kosovo", "Skopje": "North Macedonia",
    "Tirana": "Albania", "Valletta": "Malta", "Nicosia": "Cyprus",
    "Yerevan": "Armenia", "Baku": "Azerbaijan", "Tbilisi": "Georgia",
    "Kiev": "Ukraine", "Minsk": "Belarus", "Vilnius": "Lithuania",
    "Riga": "Latvia", "Tallinn": "Estonia", "Hanoi": "Vietnam",
    "Phnom Penh": "Cambodia", "Vientiane": "Laos", "Rangoon": "Myanmar",
    "Manila": "Philippines", "Kathmandu": "Nepal", "Colombo": "Sri Lanka",
    "Dhaka": "Bangladesh", "Thimphu": "Bhutan", "Male": "Maldives",
    "Islamabad": "Pakistan", "Kabul": "Afghanistan", "Tashkent": "Uzbekistan",
    "Dushanbe": "Tajikistan", "Ashgabat": "Turkmenistan", "Bishkek": "Kyrgyzstan",
    "Nur-Sultan": "Kazakhstan", "Ulaanbaatar": "Mongolia", "Pyongyang": "North Korea",
    "Bandar Seri Begawan": "Brunei", "Taipei": "Taiwan", "Hong Kong": "Hong Kong",
    "Macau": "Macau", "Canberra": "Australia", "Rabat":"Morocco"
}

Accessing a value from a dictionary is done by providing a key. For instance:

city = "Jakarta"
country = capital_cities[city]
print(city " is the capital city of " + country)

To access a random key from a dictionary, we can first create a list of all the available keys. The we can extract a random value from this list:

keys = list(capital_cities)
city = random.choice(keys)
country = capital_cities[city])
print(city " is the capital city of " + country)

Python Quiz

Your task is to use the two data structures provided in the code below to complete the quiz. You will need your program to:

    Randomly select a capital city from the dictionary of capital cities
    Randomly select four non capital cities from the list of cities
    Merge the selected capital city and the 4 non capital cities into a single list
    Shuffle the selected cities to present them in a random order
    Prompt the player to guess which of the 5 cities is a capital city
    Check if the player is correct and give some feedback either “Correct: Paris is the capital of France” or “Incorrect answer. The correct answer was Paris which is the capital of France”
    Implement a scoring system (1 point per correct answer) and inform the user of their score
    Keep asking questions and end the game when the player guesses incorrectly

Python Code

Here is the Python code with our two data structure.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

CPU Design using Logic Gates

Let’s embark on an exciting journey to dissect and understand a small, fully functional CPU made entirely of logic gates. This design serves as a proof of concept, illustrating how the main components of a CPU work together to execute a program stored in memory using the Fetch-Decode-Execute cycle.

In this exploration, we will dive deep into the intricacies of a low-spec CPU that, despite its simplicity, encapsulates the fundamental principles of modern computing. Our CPU design includes a clock, a control unit, an ALU, a data store with 4 bytes of data, an instruction store with 8 instructions (each 4 bits long, with 2 bits for the opcode and 2 bits for the operand), and a memory unit acting as RAM or CPU cache, also consisting of 4 bytes of data.

You can access and test our demo CPU by clicking on the following picture:

The logic gates circuits in our CPU contain all the essential components that make up a central processing unit. You can find out more about these essential components using the tab belows:

CPU ClockControl UnitALUAccumulatorData StoreProgram/Instruction StoreMemory UnitMultiplexers
Clock: The heartbeat of our CPU, the clock synchronises all operations, ensuring that each component works in harmony. It generates regular pulses that dictate the timing of the Fetch-Decode-Execute cycle. The clock of the CPU directly controls the Program Counter (PC), an essential register in the FDE cycle to implement sequencing: allowing the CPU to fetch decode and execute one instruction at a time, in sequence.

You can find out more on how to build a program counter using logic gates (and d-type flip-flop circuits)

Note, that in our CPU design we have used a 3-bit program counter, counting from 0 to 7 using the following circuit. The PC will be used by the control Unit to fetch the instruction from the instruction store at the address given by the Program Counter.

Control Unit: The control unit is responsible for directing the operations of all other components within the CPU. It interprets (decodes) the instructions fetched from the instruction store and generates the necessary control signals to execute them. The main logic gates circuit of the control unit is the decoder which decodes the opcode of an instruction. In our CPU, the opcode is made of 2 bits which are used to represent four possible instructions.

You can read more about binary decoder circuits using logic gates.
The table below list the 4 opcodes that our control unit can decode.

Instruction Opcode Mnemonic Purpose
00 HLT Halt the execution of the program. (Note that the provided CPU design also includes a x-HLT switch that bet turned on to ignore/bypass HLT instructions.
01 LDA Use to load a 8-bit value from the data store at a given address (the operand) into the accumulator. e.g. LDA 01 to load the value at address 01 from the data store into the accumulator
10 STA To store the value currently held in the accumulator within the memory unit at a specified address (the operand). e.g. STA 10
11 ADD To add a value from the memory unit at a specified address (the operand) to the accumulator and store the result within the accumulator.
ALU (Arithmetic Logic Unit): Our ALU is designed to perform binary addition on 2 bytes of data. While simple, it demonstrates the core arithmetic operations that are the foundation of more complex computations.
Within the ALU, binary additions are completed using a combination of Half-Adders and Full-Adders logic gates circuits. You can read more about half-adder and full-adder circuits.

Here is a Full-Adder circuit used to add 3 bits together. Click on this circuit to test it.

Note that a more advanced ALU should include other circuits to perform other arithmetic and logic operations such as binary subtractions and binary comparisons.

Accumulator: The accumulator is a special register that temporarily holds data during arithmetic and logical operations. It plays a crucial role in the execution of instructions by storing intermediate results. To temporary store the result of an instruction we are using 8 D-Type flip-flop circuits. The main purpose of a D-Type flip-flop circuit is to store one bit of data. You can read more about D-Type flip-flop circuits.

4-Byte Data Store: This small data store holds the data that the CPU needs to process. It is a simplified version of the registers found in more complex CPUs. Our data store consists of on-off switches which let you change the data being processed by the CPU. An alternative that was used in early computers was to use punched cards to store the data instead of these on-off switches.

Instruction Store: With a capacity of 8 instructions, each 4 bits long, the instruction store holds the program that the CPU will execute. Each instruction consists of an opcode and an operand, which together define the operation to be performed. Our instruction store consists of on-off switches which let you change the instructions being processed by the CPU. Early computers used punched cards instead of these on-off switches.

Note that our CPU uses a different format for the data store (storing data in blocks of 8 bits) and for the instruction store (using 4 bits per instruction), hence the design use two distinct stores for storing the data and the instructions of our program. This means that this CPU differs from the Von Neumann Processor architecture where data and instructions are stored together in primary memory (the memory unit of the CPU or in the RAM). You can read more about the Von Neumann Processor architecture.

4-Byte Memory Unit: Acting as RAM or CPU cache, this memory unit stores data that can be quickly accessed by the CPU. It is an essential component for efficient data retrieval and storage. In this design, the memory unit is part of our CPU and can only store 4 Bytes of data using 4 different memory locations. The MAR and MDR registers are connected to a multiplexer to retrieve the data (Memory Data Register) stored in the memory unit at a specific address (Memory Address Register) In a CPU or within the RAM of a computer system, bits of data are stored using D-Type flip flop circuits.

You can read more on how to design and operate a 4-Byte RAM using logic gates and test the circuit by clicking on the picture below:

Multiplexers: The three set of Multiplexers from our CPU are crucial for fetching data or instructions from the data store, the instruction store, or the memory unit. They act as switches, directing the flow of data within the CPU based on the control signals generated by the control unit. You can read more on how multiplexers are used to fetch data from memory. Here is a multiplexer to retrieve 1 bit of data from four different memory addresses (using a 2-bit address)

Operating the CPU

To operate this CPU you will first need to input your set of instructions (program) and your data in the instruction store and the data store.
Per default the following data is used:

Data Store
Address Binary Value Hexadecimal Value Denary Value
00 00000001 #01 1
01 00000100 #04 4
10 00001010 #0A 10
11 00000000 #00 0

Then you can load your set of instructions (program) in the instruction store. For this demonstration we are using the following program:

Instruction Store
Address Instruction (Binary format) Low Level Instruction Description
0 000 01 00 LDA 00 Load the value at the address 00 from the data store into the accumulator
1 001 10 00 STA 00 Store the accumulator value in the memory unit at the address 00
2 010 01 01 LDA 00 Load the value at the address 01 from the data store into the accumulator
3 011 11 00 ADD 01 Overwrite the accumulator value with the sum of the accumulator and the value in the memory unit at the address 00
4 100 10 01 STA 01 Store the accumulator value in the memory unit at the address 01
5 101 01 10 LDA 10 Load the value at the address 10 from the data store into the accumulator
6 110 11 01 ADD 10 Overwrite the accumulator value with the sum of the accumulator and the value in the memory unit at the address 01
7 111 10 10 STA 10 Store the accumulator value in the memory unit at the address 10

The aim of this program is to calculate the sum of the three numbers stored in the first three addresses of the data store. After completing execution of this program the memory unit should contain:

  • The first value of the data store at address 00: value #01 = 1
  • The sum of the first two values of the data store at address 01: value #01 + #04 = #05 = 5
  • The sum of the first three values of the data store at address 10: value #01 + #04 + #0A = #0F = 15

This should be the state of the memory unit after execution of this program:

Note that as we are not using any HLT instruction, the program will automatically and continuously repeats itself as after reaching value 7, the program counter will reset itself to 0.

You can however stop the program at any time using the on/off switch next to the clock.

As the CPU circuit runs in the web-browser, you will find that its output is unpredictable if you leave or minimise the browser window while it is still running. To avoid this, make sure to stay in the same window while the CPU is running. If needs be, you may need to reload the page at any time to reset the CPU.

Your Turn

The main characteristic of a computer system is that it should be able to run different programs. Your task is to use the switches of both the data store and the instruction store to load your own data and write and test your own computer programs!

Designing a 4-Byte RAM Circuit using Logic Gates

In the world of digital electronics, memory storage is a fundamental concept that underpins the functionality of computers and other digital systems. At the heart of these systems are logic gates and circuits that work together to store and retrieve data efficiently. Today, we’re going to delve into the design of a logic gates circuit capable of storing 4 bytes of information, essentially creating a Random Access Memory (RAM) of 4 bytes.

The Role of D-Type Flip Flops

Central to our design are D-type flip flops, which are crucial for storing bits of data. A D-type flip flop, or Delay flip flop, is a type of bistable logic gates circuit used to delay the change of state of its output until triggered by a clock signal (connected to the Enabler input of the circuit). This characteristic makes it ideal for memory storage because it can “remember” its input state even after the input has changed, provided that the clock signal has not triggered a new update. In our 4-byte RAM circuit, each bit of data will be stored using these D-type flip flops, ensuring that our memory can retain information reliably.

A D-Type Flip-Flop circuit is built using four NAND logic gates connected as follows:
D-Type-Flip-Flop-Logic-Gates

We represent a D-Type Flip-Flop Circuit as follows. You can change the input values D and E by clicking on the corresponding buttons below to see the impact on the outputs Q and Q.





D-Type-Flip-Flop-Circuit




You can also test the behaviour of a D-Type flip-flop circuit using our online simulator:
Click on the above circuit to open in a new window.

A D-Type Flip-Flop Circuit is used to store 1 bit of information. It has two input pins (Called D (Data) and E (Enabler) and two output pins (Q and Q = NOT Q).

Understanding MDR and MAR registers

To facilitate the transfer of data between the RAM and the Central Processing Unit (CPU), we will incorporate two essential registers: the Memory Data Register (MDR) and the Memory Address Register (MAR).

  • Memory Data Register (MDR): The MDR is an 8-bit register that temporarily holds the data being transferred between the memory and the CPU. When the CPU needs to read from or write to the memory, the data is first placed in the MDR. This allows the CPU to handle data in manageable chunks, in this case, 8 bits or 1 byte at a time.

  • Memory Address Register (MAR): The MAR is a 2-bit register that specifies the address of the memory location being accessed. Since we are designing a 4-byte RAM, we need 2 bits to address each of the 4 memory locations uniquely (as 22=4). The MAR ensures that data is read from or written to the correct memory address, enabling precise data manipulation.

    Our four memory addresses will be 0=00, 1=01, 2=10 and 3=11.

Putting It All Together

By combining D-type flip flops with the MDR and MAR, we can create a functional 4-byte RAM circuit. The D-type flip flops will store the bits of data, while the MDR and MAR will manage the data transfer and addressing, respectively. This setup not only provides a clear example of how memory storage works at a fundamental level but also offers a practical application of logic gates in digital electronics.

Below is our 4-Byte RAM circuit with its 32 D-Type flip-flops to store up to 32 bits of data, its 8-bit MDR and 2-bit MAR as well as a Read/Write input, that is used to decide if the RAM is in read mode or write mode.

How to use this circuit?

  1. Use the 8 switches on the left to assign a value in the MDR. (e.g. #A4 = 164 = 10100100)
  2. Use the 2 switches at the top to assign a value in the MAR. (e.g. 10 for memory location 2)
  3. Turn the R/W switch on to store the MDR value in the RAM at the chosen memory location (e.g. 2)
  4. Turn the R/W switch off and repeat these 4 steps to store different values in each of the 4 memory locations

4-Byte RAM Logic Gates Circuit

Click on the circuit below to open in a new window.

Bonsai Haven – CSS Task

Welcome to this exciting web design programming challenge designed to enhance your CSS skills. Today you’ll be working on the home page of an online shop called Bonzai Haven, an online store specialising in selling beautiful bonsai trees.

In this challenge, you will be provided with the HTML and JavaScript code for the home page of the online shop as well as a partially completed CSS file to give the page the desired look & feel. Your task is to complete the CSS to match the provided design image. This exercise will help you practice and refine your CSS skills, including layout design, styling of text pictures and buttons, and responsiveness.

Intended Home Page Design

Here is a picture of the intended final look & feel for the home page of Bonsai Haven:

CSS Syntax

A CSS rule consists of a selector and a declaration block. The declaration block contains one or more declarations separated by semicolons. Each declaration includes a CSS property name and a value, separated by a colon.

Here’s an example of a CSS rule that uses a class selector and applies several properties:

.my-class {
    color: #ff0000;
    font-size: 16px;
    margin: 10px 20px;
    padding: 20px;
    border: 1px solid black;
}

In this example, all elements with the class my-class will have red text, a font size of 16 pixels, a margin of 10 pixels (top and bottom) and 20 pixels (left and right), padding of 20 pixels, and a solid black border.

To Do List

You will complete this task step by step by adding CSS properties to apply formatting options to the relevant sections of the page. The HTML/CSS code is provided at the bottom of this page and you will be able to edit the CSS code online.

In order to complete this task you will need to familiarise yourself and research the main CSS properties using the following CSS tutorial from w3schools.

Complete each action from the following 2 tabs:

Body and Header SectionCategories / Navigation ButtonsProduct Cards
First we will focus on the main body and the top section of the page:

  • Body of the page:
      Apply a padding of 30 pixels to the body of the page
      Change the font colour to #303030
      Change the background colour to #335625
      Change the font to Raleway, sans-serif
  • Shop container:
      Set the maximum width of this element to 1400 pixels
      Set the margin to 40px (top and bottom) and auto (left and right) to center the shop on the page.
  • Shop header:
      Apply a white colour to the text
      Apply a bottom margin of 40 pixels
  • h1 tag within the shop-header:
      Change the size of the text to 3.5rem
      Apply a bottom margin of 20 pixels
  • p tag within the shop header
      Change the size of the text to 1.6rem
      Change the opacity of this element to 0.8;
      Set the maximum width attribute to 800 pixels
      Apply the Caveat, cursive font to this element
Let’s now focus on the 4 navigation buttons used to select a category of trees.

  • Categories section:
      Set a margin to 20 pixels (top and bottom) and 0 pixel (left and right)
  • Category buttons:
      Set a right margin of 15 pixels
      Set the padding to 10 pixels (top and bottom) and 20 pixels (left and right)
      Change the border radius to 25 pixels
      Apply a background colour using the following rgba code: (255,255,255,0.1)
      Apply a 1 p pixel solid border with a colour using the following rgba code: (255,255,255,0.2)
      Apply a white colour to the text
      Change the mouse cursor to display a pointer
Now let’s focus on formatting the product cards:

  • Products Grid Section:
      Change the gap to 20 pixels
  • Product Card Section:
      Change the background colour to white
      Set the border radius to 15 pixels
      Add a shadow effect using your own choice of settings for the shadow
  • Product Details Section:
      Add a padding of 25 pixels
  • Product Name Section:
      Change the font to Raleway, sans-serif
      Change size of the text to 1.5rem
      Add a bottom margin of 10 pixels
  • Product Description Section:
      Set the colour of the text to #666
      Set the line height property to 1.4
      Add a bottom margin of 20 pixels
  • Product Price Section:
      Set the colour of the text to #58873d
      Change size of the text to 1.5rem
      Set the font weight to bold
  • Add to Cart button:
      Set the background colour to #58873d
      Set the padding to 12 pixels (top and bottom) and 25 pixels (left and right)
      Set the border radius to 25 pixels
      Remove the border (set the border property to none)
      Change the mouse cursor to display a pointer
      Change the background colour to #70a751 when the user hover over the button

HTML / CSS Code

Complete the CSS code by pressing the “Edit on Codepen” button in the top right corner of the below frame.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with:

Stargate Access Code – Python Chalenge


You are aboard a state-of-the-art spaceship, a few million light-years away from planet Earth, hurtling through the cosmos on a critical mission. Following a system outage, the AI on board went into shutdown mode and locked all doors onboard the spaceship. You are now standing up in front of a locked door that blocks access to the main command centre of the ship. On the side of the door is a digital screen displaying a 6-digit number and a keypad with the 26 letters of the alphabet. Your mission, should you choose to accept it, is to unlock the door by entering a valid 3-letter combination.

How to break the code and find the 3-letter access code to unlock the gate?
The access code you need to guess is a 3-letter combination. When you multiply the ASCII values of each letter in the combination, you must get the 6-digit number displayed on the screen.

ASCII Values?

ASCII (American Standard Code for Information Interchange) values are numerical representations of characters. For example, the ASCII value of ‘A’ is 65, ‘B’ is 66, and so on. In Python, you can get the ASCII value of a character using the ord() function. You can also use the chr() function to retrieve the character matching a given ASCII value.

ascii = ord("A") # 65
print("The ASCII value for character A is :" + str(ascii))

letter = chr(90)  # Z
print("90 is the ASCII cvalue for letter " + letter)) 

Python Challenge

To solve this challenge, you will write a Python script that finds the 3-letter combination to unlock the door. Let’s dive into the world of ASCII values, loops, and a bit of mathematical magic to crack the code! Below is the digital panel to control the gate. Underneath is the Python IDE you will use to write the code to find a valid 3-letter combination.

Approach to the Solution

To solve this problem, you will use a brute-force approach. Your Python program will need to iterate through all possible 3-letter combinations of the alphabet from AAA to ZZZ and calculate the product of their ASCII values. If the product matches the given 6-digit number, your algorithm has found a valid combination!

Here’s a step-by-step outline of this approach:

  1. Generate Three-Letter Combinations: Use nested loops to generate all possible combinations of three letters. Remember, in ASCCI letter A is 65 and letter Z is 90. Use this information to implement your nested for loops.
  2. Calculate the Product of ASCII Values: For each combination, calculate the product of the ASCII values of the three letters.
  3. Compare the Product to the Given Number: If the product matches the given 6-digit number, print the combination.

Door Access Panel

Python IDE

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Stranger Code Challenge

Welcome to our latest programming challenge! This time, we’re diving into the world of Stranger Things and the challenge is based on a piece of code seen in the second series of Stranger Things (Episode 8) where, following a total blackout, some of the characters of the series are trapped inside Hawkins Lab, a secretive governmental laboratory. In order to hack into the central computer system, Bob, one of the beloved characters, has to write some code in BASIC to find the 4-digit passcode needed to access Hawkins Lab’s door access system. The code seen on the screen is written in BASIC, a programming languages used in the 1980s’. The aim of this programming challenge will be to rewrite this code in Python.

The code written by Bob is used to implement a brute force attack to test all possible combinations of 4-digit codes from 0000 to 9999 until the right passcode is found. Here is the code seen on Bob’s screen:

10 DIM FourDigitPassword INTEGER
20 FOR i = 0 TO 9
30     FOR j = 0 TO 9
40          FOR k = 0 TO 9
50                FOR l = 0 TO 9
60                      FourDigitPassword = getFourDigits (i,j,k,l)
70                      IF checkPasswordMatch(FourDigitPassword) = TRUE THEN
80                              GOTO 140
90                      END
100                NEXT l
110          NEXT k
120     NEXT j
130 NEXT i
140 PRINT FourDigitPassword
150 END

The code provided shows two functions being called: getFourDigit(i, j, k, l) on line 60 and checkPasswordMatch(FourDigitPassword) on line 70. We will assume that these

  • getFourDigit(i, j, k, l): This function takes four digits as parameters and returns a 4-digit integer. For example, if the inputs are 3, 4, 5, 6, the function should return 3456.
  • checkPasswordMatch(FourDigitPassword): This function takes a 4-digit integer and returns True if the parameter passed is the correct password, otherwise it returns False.

We will assume these two functions are part of the Hawkins Lab central computer system and we will use an import statement in Python to import and use these. However it will be part of the programming challenge to complete the code for these two functions.

Your Task

You will need to complete this task in three steps as follows:

Go into the hawkins_lab.py file in the Python IDE provided below and complete the code for the getFourDigit() function. The aim of this function is to take four integer as parameters (e.g. 3, 4, 5 and 6) and return a 4-digit integer (e.g. 3456)

Within the hawkins_lab.py file, complete the code for the checkPasswordMatch() function. The aim of this function is to take a 4-digit integer (e.g. 3456) as a parameter and compare it with the actual passcode to give access to the door access system. The correct passcode will be hardcoded within this function as 1984. If the password passed as a parameter is a match (=1984) then the function will return True, otherwise it will return False.

In the main.py file, rewrite the main code in Python from Bob’s code provided in BASIC. This is the code used to implement the Brute Force Attack to test all 4-digit passcodes from 0000 to 9999 using 4 nested loops and the two functions from hawkins-lab.py.

Python Code

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area